//
//  DZMRMStatusView.swift
//  DZMeBookRead
//
//  Created by 邓泽淼 on 2017/5/11.
//  Copyright © 2017年 DZM. All rights reserved.
//

import UIKit

class DZMRMStatusView: DZMRMBaseView {
    
    /// 电池
    private(set) var batteryView:DZMBatteryView!
    
    /// 时间
    private(set) var timeLabel:UILabel!
    
    /// 标题
    private(set) var titleLabel:UILabel!
    
    /// 计时器
    private(set) var timer:Timer?
    
    override func addSubviews() {
        
        super.addSubviews()
        
        // 背景颜色
        self.backgroundColor = UIColor.cj.color_1.withAlphaComponent(0.4)
        
        // 电池
        self.batteryView = DZMBatteryView()
        self.batteryView.tintColor = UIColor.cj.color_3
        self.addSubview(self.batteryView)
        
        // 时间
        self.timeLabel = UILabel()
        self.timeLabel.textAlignment = .center
        self.timeLabel.font = UIFont.system._12
        self.timeLabel.textColor = UIColor.cj.color_3
        self.addSubview(self.timeLabel)
        
        // 标题
        self.titleLabel = UILabel()
        self.titleLabel.font = UIFont.system._12
        self.titleLabel.textColor = UIColor.cj.color_3
        self.addSubview(self.titleLabel)
        
        // 初始化调用
        self.didChangeTime()
        
        // 添加定时器
        self.addTimer()
    }
    
    override func layoutSubviews() {
        
        super.layoutSubviews()
        // 电池
        self.batteryView.origin = CGPoint(x: width - 25, y: (height - 10)/2)
        // 时间
        let timeLabelW:CGFloat = (UIScreen.main.width / 375) * 50.0
        self.timeLabel.frame = CGRect(x: batteryView.frame.minX - timeLabelW, y: 0, width: timeLabelW, height: height)
        // 标题
        self.titleLabel.frame = CGRect(x: 0, y: 0, width: timeLabel.frame.minX, height: height)
    }

    // MARK: -- 时间相关
    
    /// 添加定时器
    func addTimer() {
        if self.timer == nil {
            self.timer = Timer.scheduledTimer(timeInterval: 15, target: self, selector: #selector(DZMRMStatusView.didChangeTime), userInfo: nil, repeats: true)
            RunLoop.current.add(self.timer!, forMode: .common)
        }
    }
    
    /// 删除定时器
    func removeTimer() {
        if self.timer != nil {
            self.timer!.invalidate()
            self.timer = nil
        }
    }
    
    /// 时间变化
    @objc private func didChangeTime() {
        
        let dateformatter = DateFormatter()
        dateformatter.dateFormat = "HH:mm"
        self.timeLabel.text = dateformatter.string(from: Date())
        self.batteryView.batteryLevel = UIDevice.current.batteryLevel
    }
    
    func setColors(textColor:UIColor) {
        self.batteryView.tintColor = textColor
        self.timeLabel.textColor = textColor
        self.titleLabel.textColor = textColor
    }
    
    /// 销毁
    deinit {
        self.removeTimer()
    }
}
